$(document).ready(function()
{
	var isAdd = false;
	// 初始化设置界面语言
	// 国际化
	$('#usmc_UserName_sc').text(usmc_i18n.prop('usmc_UserName') + i18n.prop('colon'));
	$('#usmc_UserName').text(usmc_i18n.prop('usmc_UserName') + i18n.prop('colon'));
	$('#usmc_UserPass').text(usmc_i18n.prop('usmc_UserPass') + i18n.prop('colon'));
	$('#usmc_UserRole').text(usmc_i18n.prop('usmc_UserRole') + i18n.prop('colon'));
	$('#usmc_UserPhone').text(usmc_i18n.prop('usmc_UserPhone') + i18n.prop('colon'));
	$('#usmc_UserMail').text(usmc_i18n.prop('usmc_UserMail') + i18n.prop('colon'));
	$('#usmc_UserBindIp').text(usmc_i18n.prop('usmc_UserBindIp') + i18n.prop('colon'));
	$('#usmc_UseruserExpiry').text(usmc_i18n.prop('usmc_UseruserExpiry') + i18n.prop('colon'));
	$('#usmc_UserPassExpiry').text(usmc_i18n.prop('usmc_UserPassExpiry') + i18n.prop('colon'));
	$('#usmc_UserSessinoExpiry').text(usmc_i18n.prop('usmc_UserSessinoExpiry') + i18n.prop('colon'));
	$('#usmc_user_submit').text(usmc_i18n.prop('usmc_user_submit'));
	$('#usmc_user_cancel').text(usmc_i18n.prop('usmc_user_cancel'));
	
	// 条件查询的面板
	var panel = $("#codition_div").omPanel(
	{
        iconCls : "panel_search",
        header : true,
        title : usmc_i18n.prop('usmc_user_search'),
        collapsed : false,
        collapsible : true
    });
	
	// 把查询的表单加入到面板当中
	$("#condition_query").append($("form[name='codition_form']"));
	
	// 修改图标
	$(".panel_search").removeClass("om-icon");
	$(".panel_search").removeClass("om-panel-icon");
	
	// 渲染查询按钮
	$("#cod_btn_search").omButton(
	{
		label : usmc_i18n.prop('usmc_user_search'),
		icons : 
		{
			left : '../../component/css/omui/default/images/search.png'
		},
		width : 80,
		onClick : function(event)
		{
			var username = encodeURIComponent($.trim($('input[name="cod_abyEnbName"]').val()));
			$('#usmc_userinfoGrid').omGrid("setData", '/api/usmc/v1/userbyname?username=' + username);
			// 按钮失去焦点
			$(this).blur();
		}
	});
	
	// 回车事件
	// 点击“Enter”键，触发查询事件
	$(this).keydown(function(e)
	{
		if (e.which == "13")
		{
			if(document.getElementsByName('cod_abyEnbName')[0] == document.activeElement)
			{
				var username = encodeURIComponent(encodeURIComponent($.trim($('input[name="cod_abyEnbName"]').val())));
				$('#usmc_userinfoGrid').omGrid("setData", '/api/usmc/v1/userbyname?username=' + username);
				
				return true;
			}
		}
	});
	
	// 渲染清空按钮
	$("#cod_btn_clear").omButton(
	{
		label : usmc_i18n.prop('usmc_user_reset'),
		icons : 
		{
			left : '../../component/css/omui/default/images/clear.png'
		},
		width : 80,
		onClick : function(event)
		{
			$('input[name=cod_abyEnbName]').val('');
			$('input[name=cod_abyEnbName]').focus();

			// 按钮失去焦点
			$(this).blur();
		}
	});
	
	
	
	
	if(window.parent.currUser != 'root' && window.parent.currUser != 'raisecom')
	{
		// 初始化botton按钮
		$('#buttonbar').omButtonbar(
		{
			btns :
			[
				{
					label : usmc_i18n.prop('usmc_modify'),
					id : "usmc_user_modify",
					icons :
					{
						left : '../../component/css/omui/default/images/edit_hover.png'
					},
					onClick : function()
					{
						modifyUser();
					}
				}
			]
		});
	}
	else
	{
		// 初始化botton按钮
		$('#buttonbar').omButtonbar(
		{
			btns :
			[
				{
					label : usmc_i18n.prop('usmc_pass_reset'),
					id : "usmc_user_pass_reset",
					icons :
					{
						left : '../../component/css/omui/default/images/init_pwd.png'
					},
					onClick : function()
					{
						
						passReset();
					}
				},
				
				{
					separtor : true
				},
				
				{
					label : usmc_i18n.prop('usmc_delete'),
					id : "usmc_user_delete",
					icons :
					{
						left : '../../component/css/omui/default/images/del_hover.png'
					},
					onClick : function()
					{
						
						deleteUser();
					}
				},
				
				{
					separtor : true
				},
				
				{
					label : usmc_i18n.prop('usmc_modify'),
					id : "usmc_user_modify",
					icons :
					{
						left : '../../component/css/omui/default/images/edit_hover.png'
					},
					onClick : function()
					{
						modifyUser();
					}
				},
				
				{
					separtor : true
				},
				
				{
					label : usmc_i18n.prop('usmc_add'),
					id : "usmc_user_add",
					icons :
					{
						left : '../../component/css/omui/default/images/add_hover.png'
					},
					onClick : function()
					{
						addUser();
					}
				}
			]
		});
	}
	
	// 创建表格
	$("#usmc_userinfoGrid").omGrid(
	{
		dataSource : "/api/usmc/v1/userget",
		limit : Omui.TABLE_ROWS,
		height : Omui.TABLE_HEIGHT,
		singleSelect : true,
		showIndex : true,
		colModel :
		[
			{
				header : usmc_i18n.prop("usmc_UserName"),
				name : 'userName',
				width : 240,
				align : 'left',
				wrap : true
			},
			
			/*{
				header : usmc_i18n.prop("usmc_UserRole"),
				name : 'userRole',
				width : 180,
				align : 'left',
				renderer : function(v, rowData , rowIndex)
				{
					if("1" == v)
					{
						return usmc_i18n.prop("com_raisecom_itms_hnb_tdHnbState1");
					}
					else
					{
						return usmc_i18n.prop("com_raisecom_itms_hnb_tdHnbState2");
					}
				}
			},*/

			{
				header : usmc_i18n.prop("usmc_UserPhone"),
				name : 'userPhone',
				width : 300,
				align : 'left'
			},
			
			{
				header : usmc_i18n.prop("usmc_UserMail"),
				name : 'userMailbox',
				width : 300,
				align : 'left'
			},
			
			{
				header : usmc_i18n.prop("usmc_UserBindIp"),
				name : 'userSafeAddress',
				width : 300,
				align : 'left'
			}
		   /*,
					
			{
				header : usmc_i18n.prop("usmc_UseruserExpiry"),
				name : 'userExpiryDate',
				width : 180,
				align : 'left'
			},
			
			{
				header : usmc_i18n.prop("usmc_UserPassExpiry"),
				name : 'userPassExpiryDate',
				width : 180,
				align : 'left'
			},
			
			{
				header : usmc_i18n.prop("usmc_UserSessinoExpiry"),
				name : 'userSessionTime',
				width : 180,
				align : 'left'
			}*/
		],
		onRefresh : function(data, testStatus, XMLHttpRequest, event)
		{
			// 隐藏勾选框
			$(".checkboxCol").hide();
		}
	});
	
	// 控制表格字段的显示
	//controller_table_filed("../systemUsersServlet?method=gridLevel", "systemUsers", colModel, parent.loginName);
	
	// 新增按钮
	var addUser = function()
	{
		isAdd = true;
		showDialog(usmc_i18n.prop('usmc_add'));
	};
	
	// 修改信息
	var modifyUser = function()
	{
		isAdd = false;
		var selections = $('#usmc_userinfoGrid').omGrid('getSelections', true);
		
		if ((selections[0].userName != window.parent.currUser)
			&&(window.parent.currUser != 'root')
			&&(window.parent.currUser != 'raisecom'))
		{
			$.omMessageTip.show(
			{
				type : 'warning',
				title : i18n.prop('alert'),
				content : i18n.prop('user_modify_no_rule'),
				timeout : 1500
			});
			return false;
		}
		
		if (selections.length == 0)
		{
			alertUnCheckWarn();
			return false;
		}
		
		showDialog(usmc_i18n.prop('usmc_modify'), selections[0]);
	};
	
	// 删除信息
	var deleteUser = function()
	{
		var selections = $('#usmc_userinfoGrid').omGrid('getSelections', true);
		if (selections.length == 0)
		{
			alertUnCheckWarn();
		}
		else
		{
			$.omMessageBox.confirm(
			{
				title : i18n.prop("alert"),
				content : i18n.prop("deleteContent"),
				onClose : function(value)
				{
					if (value)
					{
						// user ID
						var request =
						{
							userID : selections[0].userID
						};
						
						// 提交删除请求
						$.ajax(
						{
							type : 'POST',
							url : '/api/usmc/v1/userdel',
							dataType : 'json',
							data : JSON.stringify(request),
							contentType : 'application/json',
							success : function(msg)
							{
								// 提示消息
								if (msg.result == "0")
								{
									// 更新表格
									$('#usmc_userinfoGrid').omGrid('reload');
									
									// 删除成功提示
									alertSuccess();
								}
								else
								{
									// 删除失败提示
									alertFail();
								}
							}
						});
					}
				}
			});
		}
	};
	
	// 重置密码
	var passReset = function()
	{
		var selections = $('#usmc_userinfoGrid').omGrid('getSelections', true);
		if (selections.length == 0)
		{
			alertUnCheckWarn();
		}
		else
		{
			$.omMessageBox.confirm(
			{
				title : usmc_i18n.prop('usmc_alert'),
				content : usmc_i18n.prop('usmc_pass_cfreset'),
				onClose : function(value)
				{
					if (value)
					{
						// user name
						var request =
						{
							username : selections[0].userName,
							newpassword : ict_framework_func1("123456")
						};
						
						// 提交重置请求
						$.ajax(
						{
							type : 'POST',
							url : '/api/usmc/v1/passreset',
							dataType : 'json',
							data : JSON.stringify(request),
							contentType : 'application/json',
							success : function(msg)
							{
								// 提示消息
								if (msg.result == "0")
								{
									// 重置成功提示
									alertSuccess();
								}
								else
								{
									// 删除失败提示
									alertFail();
								}
							}
						});
					}
				}
			});
		}
	};
	
	// 定义修改或添加的弹出框
	var dialog = $("#add_dialog-form").omDialog(
	{
		width : '50%',
		autoOpen : false,
		modal : true,
		resizable : false,
		onClose : function(event)
		{
			// 清除红框样式
			$("input").removeClass("x-form-invalid");
		}
	});
	
	// 显示修改或增加的弹出框
	var showDialog = function(title, rowData)
	{
		validator.resetForm();
		
		// 设置表格提示信息
		var trs = $('table tr', dialog);
		$($('td', trs[0])[1]).find('label').text(usmc_i18n.prop('usmc_user_nameLen'));
		$($('td', trs[1])[1]).find('label').text(usmc_i18n.prop('usmc_defaultPass'));
		
		// input disable $("#id").removeAttr("disabled");
		$("#userbingip").attr("disabled", "disabled");
		$("#useruserexpiry").attr("disabled", "disabled");
		$("#userpassexpiry").attr("disabled", "disabled");
		$("#usersessionexpiry").attr("disabled", "disabled");
		
		rowData = rowData || {};
		
		$('input[name=username]', dialog).val(rowData.userName);
		//$('input[name=userpasswd]', dialog).val(rowData.hnbIpAddr);
		$('input[name=userrole]', dialog).val(rowData.userRole);
		$('input[name=userphone]', dialog).val(rowData.userPhone);
		$('input[name=usermail]', dialog).val(rowData.userMailbox);
		
		$('input[name=userbingip]', dialog).val(rowData.userSafeAddress);
		$('input[name=useruserexpiry]', dialog).val(rowData.userExpiryDate);
		$('input[name=userpassexpiry]', dialog).val(rowData.userPassExpiryDate);
		$('input[name=usersessionexpiry]', dialog).val(rowData.userSessionTime);
		
		// username and password can not modify here
		if (isAdd)
		{
			$('input[name=username]', dialog).removeAttr("disabled");
			$('input[name=userpasswd]', dialog).removeAttr("disabled");
			$("#tr_userbingip").css("display", "none");
		}
		else
		{
			$('input[name=username]', dialog).attr("disabled", "disabled");
			$('input[name=userpasswd]', dialog).attr("disabled", "disabled");
			$('input[name=userpasswd]', dialog).val("******");
			$("#tr_userbingip").css("display", "");
		}
		
		dialog.omDialog("option", "title", title);
		dialog.omDialog("open");
	};
	
	// 弹出框取消按钮
	$('#usmc_user_cancel').click(function()
	{
		$("#add_dialog-form").omDialog("close");
		
		// 清除红框样式
		$("input").removeClass("x-form-invalid");
		return false;
	});
	
	// 弹出框确定按钮：添加or修改
	$('#usmc_user_submit').click(function()
	{
		dataSubmitDialog();
		return false;
	});
	
	// 弹出框确定按钮的具体操作
	var dataSubmitDialog = function()
	{
		if (validator.form())
		{
			var selections = $('#usmc_userinfoGrid').omGrid('getSelections', true);
			var submitData = null;
			var urls = "";
			
			if (isAdd)
			{
				$.ajax(
				{
					type : 'POST',
					url : '/api/usmc/v1/userexist?userName=' + $('input[name=username]', dialog).val(),
					success : function(msg)
					{
						// 查询到的JSON对象
						if (msg.result == "0")
						{
							submitData =
							{
								userName : $('input[name=username]', dialog).val(),
								userPasswd : ict_framework_func1($('input[name=userpasswd]', dialog).val()),
								userMailbox : $('input[name=usermail]', dialog).val(),
								userSafeAddress : $('input[name=userbingip]', dialog).val(),
								userPhone : $('input[name=userphone]', dialog).val()
								/*"userAccountTime" : "",
								"userExpiryDate" : "",
								"userExpiryDateCount" : "",
								"userID" : "",
								"userLoginCount" : "",
								"userLoginTime" : "",
								"userPassExpiryDate" : "",
								"userPassExpiryDateCount" : "",
								"userRole" : "1",
								"userSafeAddress" : "",
								"userSafeState" : "",
								"userSessionTime" : ""*/
							};
							urls = '/api/usmc/v1/useradd';
							
							userSubmit(urls, submitData);
						}
						else
						{
							$.omMessageBox.alert(
							{
								type : 'error',
								title : usmc_i18n.prop('usmc_alert'),
								content : usmc_i18n.prop('usmc_user_hasexist'),
								onClose : function(value)
								{
									
								}
							});
							return false;
						}
					}
				});
			}
			else
			{
				submitData =
				{
					userID : selections[0].userID,
					userMailbox : $('input[name=usermail]', dialog).val(),
					userName : $('input[name=username]', dialog).val(),
					userSafeAddress : $('input[name=userbingip]', dialog).val(),
					userPhone : $('input[name=userphone]', dialog).val()
					/*"userAccountTime" : "",
					"userExpiryDate" : "",
					"userExpiryDateCount" : "",
					"userLoginCount" : "",
					"userLoginTime" : "",
					"userPassExpiryDate" : "",
					"userPassExpiryDateCount" : "",
					"userPasswd" : "",
					"userRole" : "1",
					"userSafeAddress" : "",
					"userSafeState" : "",
					"userSessionTime" : ""*/
				};
				urls = '/api/usmc/v1/userupdate';
				
				userSubmit(urls, submitData);
			}
		}
	};
	
	// submit user info
	var userSubmit = function(urls, submitData)
	{
		$.ajax(
		{
			type : 'POST',
			url : urls,
			dataType : 'json',
			data : JSON.stringify(submitData),
			contentType : 'application/json',
			success : function(msg)
			{
				// 查询到的JSON对象
				if (msg.result == "0")
				{
					alertSuccess();
					// 关闭dialog
					$("#add_dialog-form").omDialog("close");
					
					// 清除红框样式
					$("input").removeClass("x-form-invalid");
					
					// 更新表格
					$('#usmc_userinfoGrid').omGrid('reload');
				}
				else
				{
					alertFail();
				}
			}
		});
		return false;
	};
	
	// 过滤字段
	var rules =
	{
		username :
		{
			required : true,
			lengthrange :
			[
				1, 32
			],
			// isQuote : true,
			// isChinese : true,
			isCorrectString : true
		},
		userpasswd :
		{
			required : true,
			lengthrange :
			[
				6, 64
			],
			isChinese : true
		},
		userbingip :
		{
			isIp : true
		},
		usermail :
		{
			// required : true,
			email: true,
			isChinese : true
		},
		userphone :
		{
			// required : true,
			isMobilPhone : true
		}	
	};
	
	// 提示消息
	var errMsgs =
	{
		username :
		{
			required : usmc_i18n.prop('usmc_not_empty'),
			lengthrange : usmc_i18n.prop('usmc_user_nameTooLong')
		},
		userpasswd :
		{
			required : usmc_i18n.prop('usmc_not_empty'),
			lengthrange : usmc_i18n.prop('usmc_passTooshort')
		},
		userbingip :
		{
			isIp : usmc_i18n.prop('usmc_ipNotRight')
		},
		usermail :
		{
			required : usmc_i18n.prop('usmc_not_empty'),
			email :	usmc_i18n.prop('usmc_user_mail_err')
		},
		userphone :
		{
			required : usmc_i18n.prop('usmc_not_empty'),
		}	
	};
	
	// 调用验证方法，创建验证对象
	var validator = new form_validator(rules, errMsgs, 'errorMsg', 'userInfoForm');
	
	// 验证特殊字符
    $.validator.addMethod("isQuote", function(value) {
        return checkQuote(value);
    }, usmc_i18n.prop('usmc_user_include_special_sign'));
	
    function checkQuote(str){
        var items = new Array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "{", "}", "[", "]", "(", ")");
        items.push(":", ";", "'", "|", "\\", "<", ">", "?", "/", "<<", ">>", "||", "//");
        // items.push("admin", "administrators", "administrator", "管理员", "系统管理员");
        // items.push("select", "delete", "update", "insert", "create", "drop", "alter", "trancate");
        str = str.toLowerCase();
        for (var i = 0; i < items.length; i++) {
            if (str.indexOf(items[i]) >= 0) {
                return false;
            }
        }
        return true;
    }
    
    // 验证是否包含中文
    $.validator.addMethod("isChinese", function(value) {
        return checkChinese(value);
    }, usmc_i18n.prop('usmc_user_include_chinese'))
    
    function checkChinese(str){
        if (escape(str).indexOf("%u") != -1) {
            return false;
        }
        else {
            return true;
        }
    }
    
    $.validator.addMethod("isMobilPhone", function(value) 
    {
    	if (0 == value.length)
    	{
    		return true;
    	}	
    	
      var regu =/(^[1][3][0-9]{9}$)|(^[1][5][0-9]{9}$)|(^[1][8][0-9]{9}$)|(^[0][1-9]{1}[0-9]{9}$)/; 
      var reg = new RegExp(regu);
      return reg.test(value);  // 手机验证 13x 15x 18x 以此类推
 
    }, usmc_i18n.prop('usmc_user_mobilphone_err'));

    $.validator.addMethod("isCorrectString", function(value) {
        var regu =/(^[a-zA-Z_0-9]*$)/; 
        var reg = new RegExp(regu);
        return reg.test(value); 
    }, usmc_i18n.prop('usmc_user_string_err'));

    parent.setIframeHeight("userManager", 600);
     
});
